package com.qin.dao;

import java.sql.SQLException;
import java.util.List;

import com.qin.entity.Comment;

import cn.hutool.db.Db;
import cn.hutool.db.Entity;
import cn.hutool.db.handler.BeanHandler;

/**
 * 操作comment类
 * @author BestRiven
 *
 */
public class CommentDao {
	
	/**
	 * 插入一条评论
	 * @param comment 要插入的评论
	 * @return 自增id
	 */
	public Long insertComment(Comment comment) {
		Entity record = Entity.parseWithUnderlineCase(comment);
		Long insertForGeneratedKey = 0L;
		try {
			insertForGeneratedKey = Db.use().insertForGeneratedKey(record);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		return insertForGeneratedKey;
	}
	
	/**
	 * 逻辑删除评论
	 * @param id 要逻辑删除评论的id
	 * @return 影响行数（0代表失败，1代表影响一行）
	 */
	public int logicDeleteComment(Long id) {
		String sql = "UPDATE `comment` SET `status` = 0 WHERE `id` = ?";
		int execute =  0;
		try {
			execute = Db.use().execute(sql, id);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		return execute;
	}
	
	/**
	 * 根据id（并且满足status=1）修改评论内容
	 * @param id 要修改评论的id
	 * @param content 评论的内容
	 * @return 影响行数（0代表失败，1代表影响一行）
	 */
	public int updateComment(Long id,String content) {
		String sql = "UPDATE `comment` SET `content` = ? WHERE `id` = ? AND `status` = 1";
		int execute = 0;
		try {
			execute = Db.use().execute(sql, content,id);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		return execute;
	}
	
	/**
	 * 根据id查询评论
	 * @param id 要查询评论的id
	 * @return 查到的评论
	 */
	public Comment queryCommentById(Long id) {
		Entity where = Entity.create("comment").set("id", id).set("status", 1);
		Comment comment = null;
		try {
			comment = Db.use().find(where,  new BeanHandler<Comment>(Comment.class));
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		return comment;
	}
	
	/**
	 * 根据图书的id查询所有的评论
	 * @param id 图书id
	 * @return 所有的评论，用List封装
	 */
	public List<Comment> queryAllCommentByBookId(Long id){
		List<Comment> comments = null;
		try {
			comments = Db.use().find(Entity.create("comment").set("book_id", id).set("status", 1),Comment.class);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		return comments;
	}
	
}
